package com.yc.forum.servlet;

import com.yc.forum.dao.CategoryDao;
import com.yc.forum.dao.RedisDao;
import com.yc.forum.util.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 通过问题id获取回复帖子的信息和帖子发布者信息，分页查询
 */
@WebServlet(name="QueryPostByProblemIdServlet",value="/QueryPostByProblemIdServlet.s")
public class QueryPostByProblemIdServlet extends HttpServlet {
    CategoryDao categoryDao=new CategoryDao();
    RedisDao redisDao=new RedisDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-----------------init QueryPostByProblemIdServlet--------------------");
        //通过问题id获取到相应的回复帖子的信息
        String problemId=req.getParameter("problemId");
        int begin=Integer.parseInt(req.getParameter("page"));
        int size=Integer.parseInt(req.getParameter("size"));
        //查找回复帖子
        List<Map<String,Object>> list= categoryDao.selectPostWithLimitOrderByTime(problemId,begin,size);
        //去除html标签，获取点赞、收藏、评论数量
        for (int i = 0; i < list.size(); i++) {
            //得到map
            Map<String,Object> map=list.get(i);
            //获取body内容
            String body=""+map.get("body");
            //调用去除html标签的工具
            String newbody=Utils.takeOutHtmlTab(body);
            //更新map
            map.put("body",newbody);

            //从redis中获取该帖子的点赞、收藏、评论数量
            Map<String,String> someSum=redisDao.queryPostSomeSumById(""+map.get("id"));
            //添加到map中
            map.putAll(someSum);

            //得到单独的年月日
            Map<String,Object> date=Utils.dateToYearMonthDay(""+map.get("begintime"));
            //添加到map中
            map.putAll(date);

            //更新list
            list.set(i,map);
        }
        System.out.println("postlist="+list.toString());
        Utils.toJson(list,resp);
    }
}
